<template>
  <div class="container">
    <el-button
      type="primary"
      @click="handleAddData"
      icon="Plus"
      class="add-button"
    >
      添加数据
    </el-button>

    <el-card shadow="hover" class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="学期筛选">
          <el-select
            v-model="filterForm.term"
            placeholder="请选择学期"
            clearable
            filterable
            class="term-select"
          >
            <el-option
              v-for="term in terms"
              :key="term"
              :label="term"
              :value="term"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleFilter"
            icon="Refresh"
          >
            刷新
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="hover" class="table-card">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="table_loading"
        stripe
        size="medium"
        highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column prop="term" label="学期" width="200">
          <template #default="{ row }">
            <el-tag type="info" effect="plain">{{ row.term }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="report_name" label="报备名" width="180" />
        <el-table-column prop="report_fields" label="报备字段" min-width="400">
          <template #default="{ row }">
            <div v-if="row.report_fields" class="field-container">
              <div v-for="(field, index) in parseReportFields(row.report_fields)" :key="index" class="field-item">
                <div class="field-header">
                  <el-tag type="success" size="small">{{ field.label }}</el-tag>
                  <span class="field-key">{{ field.key }}</span>
                </div>
                <div class="field-options">
                  <el-tag
                    v-for="(option, optIndex) in field.choice"
                    :key="optIndex"
                    type="info"
                    size="small"
                    effect="plain"
                    class="option-tag"
                  >
                    {{ option }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div v-else>
              <el-tag type="danger">无报备字段</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="report_description" label="报备说明" width="180" />
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="danger"
              size="small"
              @click="handleClickDelete(scope.row)"
              :loading="delete_loading"
              icon="Delete"
              plain
            >
              删除
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleClickEdit(scope.row)"
              :loading="edit_loading"
              icon="Edit"
              plain
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="filterForm.page"
          :page-size="10"
          layout="prev, pager, next, jumper, total"
          :total="total_datas"
          @current-change="handlePageChange"
          background
        />
      </div>
    </el-card>

    <AddData ref="addDataRef" :tableType="tableType" :isAdmin="true" @refresh-table="refreshTable" />
    <EditData ref="editDataRef" :tableType="tableType" :isAdmin="true" @refresh-table="refreshTable" />

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage } from "element-plus";

import {formDataApi, jsonApi} from "@/global.js";
import AddData from "@/components/Main/NewReportManagement/ReportFiledAdmin/AddData.vue";
import EditData from "@/components/Main/NewReportManagement/ReportFiledAdmin/EditData.vue";


const props = defineProps({
  tableType: {
    type: String,
    required: true
  }
});

// 状态管理
const tableData = ref([]);
const total_datas = ref(0);
const table_loading = ref(true);
const delete_loading = ref(false);
const edit_loading = ref(false);

// 筛选表单
const filterForm = reactive({
  term: '',
  page: 1,
});

// 学期选项
const terms = ref([
  '2023-2024学年秋季学期',
  '2023-2024学年春季学期',
  '2024-2025学年秋季学期',
  '2024-2025学年春季学期',
  '2025-2026学年秋季学期',
  '2025-2026学年春季学期',
  '2026-2027学年秋季学期',
  '2026-2027学年春季学期',
  '2027-2028学年秋季学期',
  '2027-2028学年春季学期',
  '2028-2029学年秋季学期',
  '2028-2029学年春季学期',
]);

// 根据当前月份设置默认学期
const getDefaultTerm = () => {
  const now = new Date();
  const month = now.getMonth() + 1; // 月份从1开始
  const year = now.getFullYear();

  // 8月-1月为秋季学期
  if (month >= 8 || month <= 1) {
    // 如果是1月，学年是上一年-当年
    if (month <= 1) {
      return `${year-1}-${year}学年秋季学期`;
    } else {
      return `${year}-${year+1}学年秋季学期`;
    }
  }
  // 2月-7月为春季学期
  else {
    return `${year-1}-${year}学年春季学期`;
  }
};

// 解析报备字段
const parseReportFields = (fields) => {
  try {
    if (typeof fields === 'string') {
      return JSON.parse(fields);
    }
    return fields;
  } catch (e) {
    console.error('解析报备字段失败:', e);
    return [];
  }
};

// 初始化数据
onMounted(() => {
  // 设置默认学期
  filterForm.term = getDefaultTerm();
  refreshTable();
});

// 刷新表格数据
const refreshTable = async () => {
  try {
    table_loading.value = true;
    let formData = new FormData();
    formData.append('page', filterForm.page);
    formData.append('term', filterForm.term);

    const response = await formDataApi('/newreport/field/get/', formData);

    if (!response.ok) {
      throw new Error(`API 请求失败: ${response.status}`);
    }

    const data = await response.json();

    // 确保数据结构正确
    if (data && data.datas && Array.isArray(data.datas)) {
      tableData.value = data.datas;
      total_datas.value = data.total_datas || 0;
    } else {
      throw new Error("API 返回的数据格式不正确");
    }
  } catch (error) {
    console.error("加载数据失败:", error);
    ElMessage.error(`数据加载失败: ${error.message}`);
    tableData.value = [];
    total_datas.value = 0;
  } finally {
    table_loading.value = false;
  }
};

// 事件处理
const handleFilter = () => {
  filterForm.page = 1; // 重置到第一页
  refreshTable();
};

const handlePageChange = (newPage) => {
  filterForm.page = newPage;
  refreshTable();
};

// 在父组件中
const addDataRef = ref(null);
const editDataRef = ref(null);

const handleAddData = () => {
  addDataRef.value.open();
};

const handleClickDelete = async (row) => {
  delete_loading.value = true;
  const response = await jsonApi('/newreport/field/delete/', JSON.stringify({id: row.id}))
  if (response.ok) {
    ElMessage.success('删除成功');
    await refreshTable();
  } else {
    ElMessage.error('删除失败');
  }
  delete_loading.value = false;
};

const handleClickEdit = (row) => {
  editDataRef.value.open(row);
};

const handleSucceedAdd = () => {
  refreshTable();
};

const handleSucceedEdit = () => {
  refreshTable();
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.add-button {
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.term-select {
  width: 300px;
}

.table-card {
  border-radius: 8px;
}

.field-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 8px 0;
}

.field-item {
  background: #f8fafc;
  border-radius: 6px;
  padding: 10px;
  border-left: 3px solid #409eff;
}

.field-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.field-key {
  color: #606266;
  font-size: 12px;
}

.field-options {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.option-tag {
  margin-right: 4px;
  margin-bottom: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}
</style>